using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Widget;
using Android.Views;

namespace Granite.Axml
{
	public abstract class BindingActivity<T> : NavigationActivity<T> where T : NavigationViewModel, new()
	{

		protected override void OnPause()
		{
			base.OnPause();

			//deactivate bindings so that they cannot prevent garbage collection of the view
			foreach (var item in m_Bindings)
				item.Deactivate();
		}

		protected override void OnPostResume()
		{
			base.OnPostResume();

			//activate any bindings
			foreach (var item in m_Bindings)
				item.Activate();
		}

		public override void OnContentChanged()
		{
			base.OnContentChanged();
			foreach (var item in m_Bindings)
				item.Deactivate();
			m_Bindings.Clear();
		}

		readonly List<BindingBase> m_Bindings = new List<BindingBase>();

		protected void BindText(TextView control, object source, string bindingPath, BindingMode mode)
		{
			m_Bindings.Add(new TextViewTextBinding(control, source, bindingPath, mode));
		}

		protected void BindText(int resourceId, object source, string bindingPath, BindingMode mode)
		{
			var control = FindViewById<TextView>(resourceId);
			BindText(control, source, bindingPath, mode);
		}
		
		/// <summary>
		/// Remove all of the bindings against the indicated control.
		/// </summary>
		/// <param name="resourceId"></param>
		/// <remarks>This is generally called when dynamically removing a control from the screen.</remarks>
		protected void RemoveBindings(int resourceId)
		{
			var control = FindViewById<TextView>(resourceId);
			RemoveBindings(control);
		}

		/// <summary>
		/// Remove all of the bindings against the indicated control.
		/// </summary>
		/// <param name="control"></param>
		/// <remarks>This is generally called when dynamically removing a control from the screen.</remarks>
		protected void RemoveBindings(View control)
		{
			var deadList = m_Bindings.Where(b => b.Target == control).ToList();
			foreach (var item in deadList)
			{
				item.Deactivate();
				m_Bindings.Remove(item);
			}
		}
	}
}
